package com.norma.netty.study.netty.protocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author zhangchaofeng
 * @date 2020/10/5
 * @description
 */
public class NettyProtocolServerHandler extends SimpleChannelInboundHandler<NettyMessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NettyMessageProtocol msg) throws Exception {
        //接受数据
        int length = msg.getLength();
        byte[] content = msg.getContent();
        System.out.println("----->server 接收到数据len=" + length + "content=" + new String(content, StandardCharsets.UTF_8));
        System.out.println("server 接受数据包数量=" + (++count));
        //reply client
        NettyMessageProtocol messageProtocol = new NettyMessageProtocol();
        String m = UUID.randomUUID().toString();
        messageProtocol.setContent(m.getBytes(StandardCharsets.UTF_8));
        messageProtocol.setLength(m.getBytes(StandardCharsets.UTF_8).length);
        ctx.channel().writeAndFlush(messageProtocol);
    }
}
